package com.xiguaji.tiktok.v1.tiktok.blogger.controller;

import com.xiguaji.tiktok.config.exception.ParamsException;
import com.xiguaji.tiktok.utils.Ret;
import com.xiguaji.tiktok.v1.BaseController;
import com.xiguaji.tiktok.v1.product.dto.PlatformTypeEnum;
import com.xiguaji.tiktok.v1.product.dto.ReportTypeEnum;
import com.xiguaji.tiktok.v1.tiktok.aweme.service.AwemeService;
import com.xiguaji.tiktok.v1.tiktok.blogger.dto.SearchData;
import com.xiguaji.tiktok.v1.tiktok.blogger.service.BloggerService;
import com.xiguaji.tiktok.v1.tiktok.music.service.MusicService;
import com.xiguaji.tiktok.v1.tiktok.permission.Limit;
import com.xiguaji.tiktok.v1.tiktok.permission.RequestLimit;
import com.xiguaji.tiktok.v1.tiktok.permission.RequestLimits;
import com.xiguaji.tiktok.v1.product.service.ProductService;
import com.xiguaji.tiktok.v1.user.log.Operation;
import com.xiguaji.tiktok.v1.user.log.ParamsType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(value = "播主",tags = {"播主"})
public class BloggerController extends BaseController {

    @Autowired
    BloggerService bloggerService;

    @Autowired
    ProductService productService;

    @Autowired
    AwemeService awemeService;

    @Autowired
    MusicService musicService;

    @Value("${tiktok.data.query.latestDays}")
    int latestDays;

    @Value("${posts.music.size}")
    int postsMusicSize;

    @Value("${posts.hashtag.size}")
    int postsHashtagSize;

    @Value("${posts.mention.size}")
    int postsMentionSize;

    @ApiOperation(value = "获取播主列表信息",notes = "获取播主分页列表信息\n" +
            "排序sort参数说明：\n" +
            "1. ALL：按传播指数排序\n" +
            "2. Views：按播放数排序\n" +
            "3. Views：按播放数排序\n" +
            "4. Likes：按点赞数排序\n" +
            "5. Reviews：按评论数排序\n" +
            "6. Share：按分享数排序")
    @RequestMapping(value = "blogger",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @RequestLimit(value = "PageDataLimit",property = "page,pageSize",validateType = Limit.VIEW_DATA_LIMIT)
    public String getBloggerList(String data) throws IOException, ParamsException {
        SearchData searchData = getParam(SearchData.class, URLDecoder.decode(data,"UTF-8"));
        return bloggerService.getPageByEs(searchData,getUser().getId(),getRoleId());
    }

    @ApiOperation(value = "获取博主类型列表")
    @RequestMapping(value = "blogger/type",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主类型列表")
    public String getBloggerTypeList(){
        return Ret.success("获取成功！",bloggerService.getTypeList());
    }


    @ApiOperation(value = "获取博主信息")
    @RequestMapping(value = "blogger/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主信息",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.DAY_LIMIT,paramType = ParamsType.URL)
    public String getBloggerDetail(@PathVariable long bloggerId){
        return Ret.success("OK",bloggerService.getBloggerInfo(bloggerId,getUser().getId()));
    }

    @ApiOperation(value = "获取博主指标信息")
    @RequestMapping(value = "blogger/{bloggerId}/{infoType}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主指标信息",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.DAY_LIMIT,paramType = ParamsType.URL)
    public String getBloggerData(@PathVariable long bloggerId,@PathVariable int infoType){
        int day = 6;

        if(infoType != 1){
            day = 29;
        }
        return Ret.success("OK",bloggerService.getBloggerData(bloggerId,day));
    }

    @ApiOperation(value = "获取博主信息走趋")
    @RequestMapping(value = "blogger/performance/{bloggerId}/{infoType}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主信息走趋",fetchParam = "bloggerId",paramType = ParamsType.URL)
    // @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.DAY_LIMIT,paramType = ParamsType.URL)
    public String getBloggerPerformance(@PathVariable long bloggerId,@PathVariable int infoType){
        int day = 6;

        if(infoType != 1){
            day = 29;
        }
        return Ret.success("OK",bloggerService.getBloggerPerformance(bloggerId,day));
    }

    @ApiOperation(value = "获取博主视频信息走趋")
    @RequestMapping(value = "blogger/aweme/performance/{bloggerId}/{infoType}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.DAY_LIMIT,paramType = ParamsType.URL)
    @Operation(value = "获取博主视频信息走趋",fetchParam = "bloggerId",paramType = ParamsType.URL)
    public String getBloggerAwemePerformance(@PathVariable long bloggerId,@PathVariable int infoType){
        int day = 6;

        if(infoType != 1){
            day = 29;
        }
        return Ret.success("OK",bloggerService.getBloggerAwemePerformance(bloggerId,day));
    }

    @ApiOperation(value = "获取博主视频列表",notes = "%7B%22infoType%22%3A1%2C%22sort%22%3A1%2C%22pageSize%22%3A10%2C%22page%22%3A1%7D")
    @RequestMapping(value = "blogger/aweme/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主视频列表",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimits({
            @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.DAY_LIMIT,paramType = ParamsType.URL),
            @RequestLimit(value = "BloggerAwemeLimit",property = "page,pageSize",validateType = Limit.VIEW_DATA_LIMIT)
    })
    public String getBloggerAweme(@PathVariable long bloggerId,String data) throws UnsupportedEncodingException, ParamsException {
        SearchData searchData = getParam(SearchData.class, URLDecoder.decode(data,"UTF-8"));
        val awemePageByBlogger = bloggerService.getAwemePageByBlogger(bloggerId, searchData,getUser().getId());
        return Ret.pageData(awemePageByBlogger.getTotalCount(),awemePageByBlogger.getList());
    }



    /**
     * 调用接口通知更新博主信息
     *
     * @param bloggerId
     * @return
     */
    @ApiOperation(value = "调用接口通知更新博主信息")
    @RequestMapping(value = "blogger/call/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "调用更新博主信息",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.DAY_LIMIT,paramType = ParamsType.URL)
    public String callUpdateBlogger(@PathVariable long bloggerId){
        return Ret.success("OK",bloggerService.callUpdateBlogger(bloggerId));
    }

    @ApiOperation(value = "验证是否可以解锁报告")
    @RequestMapping(value = "blogger/report/unlock/checked",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "验证是否可以解锁报告")
    public String checkedUnlockedBloggerReport(){
        String msg = "";
        Map<String,Object> result = new HashMap<>();
        if(getRoleId() >2){
            int roleReportNumber = productService.unlockedNumberByRole(getUser().getId(),getRoleId(),ReportTypeEnum.BLOGGER.getMsg());
            msg = "Your daily reports balance is "+roleReportNumber+" reports.";
            if(roleReportNumber > 0){
                msg += "Unlock this report costs 1 daily report. Do you want to continue?";
                result.put("type",1);
                return Ret.success(msg,result);
            }
        }
        int reportStarterNumber = productService.unlockedNumberByReportStarter(getUser().getId());

        if(reportStarterNumber > 0){
            msg += "Your credits reports balance is "+reportStarterNumber+". Unlock this report costs 1 credit. Do you want to continue?";
            result.put("type",2);
            return Ret.success(msg,result);
        }
        return Ret.success("Insufficient daily reports. Please try again tomorrow or purchase credits.");
    }


    @ApiOperation(value = "解锁报告")
    @RequestMapping(value = "blogger/report/unlock",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @Operation(value = "解锁报告")
    public String unlockedBloggerReport(@RequestBody String body) throws ParamsException {
        Long uid = getParam(Long.class,body,"uid");
        if(productService.isUnlocked(getUser().getId(),uid,PlatformTypeEnum.TIKTOK.getCode())){
            return Ret.success("你已解锁过了");
        }

        if(productService.unlockedByUserRole(getUser().getId(),getRoleId(),uid,PlatformTypeEnum.TIKTOK.getCode(), ReportTypeEnum.BLOGGER.getCode(), ReportTypeEnum.BLOGGER.getMsg())){
            return Ret.success("解锁成功");
        }

        if(productService.unlockedByReportStarter(getUser().getId(),uid, PlatformTypeEnum.TIKTOK.getCode(),ReportTypeEnum.BLOGGER.getCode())){
            return Ret.success("解锁成功");
        }
        return Ret.err("解锁失败");
    }

    /**
     * 获取博主粉丝画像数据
     * @param bloggerId 博主id
     * @return
     */
    @ApiOperation(value = "获取博主粉丝画像数据")
    @RequestMapping(value = "blogger/fansPortrait/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主粉丝画像数据",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "BloggerIdLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerFansPortrait(@PathVariable long bloggerId) {
        return Ret.success("success",bloggerService.getBloggerFansPortrait(bloggerId));
    }

    //===================================================发文 START=========================================================

    @ApiOperation(value = "获取博主所用的标签(解锁)")
    @RequestMapping(value = "blogger/hashtag/all/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主所用的标签")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerUseHashtags(@PathVariable long bloggerId){
        return Ret.success("success",awemeService.getAllAwemeHashtag(latestDays,bloggerId));
    }

    @ApiOperation(value = "统计博主发文星期时间段(解锁)")
    @RequestMapping(value = "blogger/aweme/week/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "统计博主发文星期时间段")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String countUseOfDay(@PathVariable long bloggerId){
        return Ret.success("success",awemeService.countUseOfDay(latestDays,bloggerId));
    }

    @ApiOperation(value = "统计博主发文小时时间段(解锁)")
    @RequestMapping(value = "blogger/aweme/hour/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "统计博主发文小时时间段")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String countUseOfHour(@PathVariable long bloggerId){
        return Ret.success("success",awemeService.countUseOfHour(latestDays,bloggerId));
    }

    @ApiOperation(value = "获取博主所用的标签列表(解锁)")
    @RequestMapping(value = "blogger/hashtag/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主所用的标签列表")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerTopHashtags(@PathVariable long bloggerId){
        return Ret.success("success",awemeService.getAwemeHashtag(latestDays,bloggerId,postsHashtagSize));
    }

    @ApiOperation(value = "获取博主所用的音乐列表(解锁)")
    @RequestMapping(value = "blogger/music/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主所用的音乐列表")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerTopMusic(@PathVariable long bloggerId){
        return Ret.success("success",musicService.analytic(latestDays,bloggerId,postsMusicSize));
    }

    @ApiOperation(value = "获取博主@博主的列表(解锁)")
    @RequestMapping(value = "blogger/mention/{bloggerId}/{stats}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主@博主的列表(解锁)")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerTopMentions(@PathVariable long bloggerId,@PathVariable int stats){
        return Ret.success("success",awemeService.getAwemeMention(latestDays,bloggerId,postsMentionSize,stats));
    }

    //===================================================发文 END=========================================================


    @ApiOperation(value = "获取博主视频列表(解锁)",notes = "%7B%22infoType%22%3A1%2C%22sort%22%3A1%2C%22pageSize%22%3A10%2C%22page%22%3A1%7D")
    @RequestMapping(value = "blogger/aweme/list/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主视频列表(解锁)",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerAwemeForReport(@PathVariable long bloggerId,String data) throws UnsupportedEncodingException, ParamsException {
        SearchData searchData = getParam(SearchData.class, URLDecoder.decode(data,"UTF-8"));
        val awemePageByBlogger = bloggerService.getAwemePageByBlogger(bloggerId, searchData,getUser().getId());
        return Ret.pageData(awemePageByBlogger.getTotalCount(),awemePageByBlogger.getList());
    }

    @ApiOperation(value = "获取博主信息(解锁)")
    @RequestMapping(value = "blogger/report/{bloggerId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主信息(解锁)",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerDetailForReport(@PathVariable long bloggerId){
        return Ret.success("OK",bloggerService.getBloggerInfo(bloggerId,getUser().getId()));
    }

    @ApiOperation(value = "获取博主指标信息(解锁)")
    @RequestMapping(value = "blogger/report/{bloggerId}/{infoType}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "获取博主指标信息(解锁)",fetchParam = "bloggerId",paramType = ParamsType.URL)
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    public String getBloggerDataForReport(@PathVariable long bloggerId,@PathVariable int infoType){
        return getBloggerData(bloggerId,infoType);
    }

    @ApiOperation(value = "获取博主视频信息走趋(解锁)")
    @RequestMapping(value = "blogger/report/aweme/performance/{bloggerId}/{infoType}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @RequestLimit(value = "ReportLimit",property = "bloggerId",validateType = Limit.REPORT_LIMIT,paramType = ParamsType.URL)
    @Operation(value = "获取博主视频信息走趋(解锁)",fetchParam = "bloggerId",paramType = ParamsType.URL)
    public String getBloggerAwemePerformanceForReport(@PathVariable long bloggerId,@PathVariable int infoType){
        return getBloggerAwemePerformance(bloggerId,infoType);
    }
}
